package com.cari.oa.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.cari.oa.domain.NewsEntity;
import com.cari.oa.util.StrUtils;

@Repository
public class NewsDao extends BaseDao<NewsEntity>{
	 /**
     * 根据ID获取实体
     * @param Id
     * @return 对象
     */
    public NewsEntity getById(String id) {
        Query query = getSession().createQuery("from NewsEntity where id = :id");
        query.setString("id", id);
        return (NewsEntity)query.uniqueResult();
    }
    
    /**
     * 判断该英文名实体对象是否存在
     * @param enname 系统字典项英文名
     * @return 是否存在
     */
    public boolean existByTitle(String title) {
        Query query = getSession().createQuery("select count(*) from NewsEntity where title = :title");
        query.setString("title", title);
        Long count = (Long)query.uniqueResult();
        return count > 0;
    }
    
    /**
     * 分页查询系统字典项实体对象
     * @param title 系统字典项英文名
     * @param page 当前页
     * @param size 每页条数
     * @return 分页实体
     */
    public List<NewsEntity> getPage(String title, int page, int size) {
    	List<Object> params = new ArrayList<Object>();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("from NewsEntity i where 1=1 ");

        if(StrUtils.isNotEmpty(title)) {
            stringBuilder.append("and i.title like ? ");
            params.add("%" + title + "%");
        }

        return getPage(stringBuilder.toString(), page, size, params.toArray());
    }
    
    /**
     * 查询的记录数
     * @param title 系统字典项英文名
     * @return 记录数
     */
    public long getCount(String title) {
    	List<Object> params = new ArrayList<Object>();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("select count(*) from NewsEntity i where 1=1 ");
        
        if(StrUtils.isNotEmpty(title)) {
            stringBuilder.append("and i.title like ? ");
            params.add("%" + title + "%");
        }

        Query query = getSession().createQuery(stringBuilder.toString());
        for (int i = 0; i < params.size(); i++) {
            query.setParameter(i, params.get(i));
        }
        return (Long)query.uniqueResult();
    }
}
